<?php

if(!defined('IN_JOSEPPE')) {
	exit('Access Denied');
}

function js_unescape($str)
{
	$ret = '';
	$len = strlen($str);
	for ($i = 0; $i < $len; $i++)
	{
		if ($str[$i] == '%' && $str[$i+1] == 'u')
		{
			$val = hexdec(substr($str, $i+2, 4));
			if ($val < 0x7f)
				$ret .= chr($val);
			elseif($val < 0x800)
				$ret .= chr(0xc0|($val>>6)).chr(0x80|($val&0x3f));
			else
				$ret .= chr(0xe0|($val>>12)).chr(0x80|(($val>>6)&0x3f)).chr(0x80|($val&0x3f));
			$i += 5;
		}
		elseif ($str[$i] == '%')
		{
			$ret .= urldecode(substr($str, $i, 3));
			$i += 2;
		}
		else $ret .= $str[$i];
	}
	return $ret;
}

function phpescape($str)
{
	$sublen=strlen($str);
	$retrunString="";
	for ($i=0;$i<$sublen;$i++)
	{
		if(ord($str[$i])>=127)
		{
			$tmpString=bin2hex(iconv("gb2312","ucs-2",substr($str,$i,2)));
			//$tmpString=substr($tmpString,2,2).substr($tmpString,0,2);window下可能要打开此项
			$retrunString.="%u".$tmpString;
			$i++;
		} else {
			$retrunString.="%".dechex(ord($str[$i]));
		}
	}
	return $retrunString;
}

/******************************************************************
* PHP截取UTF-8字符串，解决半字符问题。
* 英文、数字（半角）为1字节（8位），中文（全角）为3字节
* @return 取出的字符串, 当$len小于等于0时, 会返回整个字符串
* @param $str 源字符串
* $len 左边的子串的长度
****************************************************************/
function utf_substr($str, $len) {
	$len = $len * 3;
    for($i = 0; $i < $len; $i++) {
		$temp_str = substr($str, 0, 1);
		if(ord($temp_str) > 127) {
			$i = $i + 2;
			if($i<$len) {
				$new_str[] = substr($str, 0, 3);
				$str = substr($str, 3);
			}
		}
		else {
			$new_str[] = substr($str, 0, 1);
			$str = substr($str, 1);
		}
    }
    return join("", $new_str);
}

//统计代码
function updatestat($type, $primary=0){
	global $_SGLOBAL, $_SCONFIG;

	if(empty($_SGLOBAL['supe_uid']) || empty($_SCONFIG['updatestat'])) return false;

	if($primary) {
		//去重
		$setarr = array(
			'uid' => $_SGLOBAL['supe_uid'],
			'daytime' => $_SGLOBAL['tadaytime'],
			'type' => $type
		);
		if(getcount('statuser', $setarr)) {
			return false;
		} else {
			inserttable('statuser', $setarr);//插入当天数据
		}
	}
	if(getcount('stat', array('daytime'=>$nowdaytime))) {
		$_SGLOBAL['db']->query("UPDATE ".tname('stat')." SET `$type`=`$type`+1 WHERE daytime='$nowdaytime'");
	} else {
		//删除昨天的防重数据
		$_SGLOBAL['db']->query("DELETE FROM ".tname('statuser')." WHERE daytime != '$nowdaytime'");
		//插入统计
		inserttable('stat', array('daytime'=>$nowdaytime, $type=>'1'));
	}
}
//对话框
function showmessage($message, $url_forward='', $second=2) {
	global $_SGLOBAL;

	obclean();
	
	//显示
	if(empty($_SGLOBAL['inajax']) && $url_forward && empty($second)) {
		header("HTTP/1.1 301 Moved Permanently");
		header("Location: $url_forward");
	} else {
		if($_SGLOBAL['inajax']) {
			if($url_forward) {
				$message = "<a href=\"$url_forward\">$message</a><ajaxok>";
			}
			//$message = "<h1>".$_SGLOBAL['msglang']['box_title']."</h1><a href=\"javascript:;\" onclick=\"hideMenu();\" class=\"float_del\">X</a><div class=\"popupmenu_inner\">$message</div>";
			echo $message;
			//echo ob_get_contents();
		} else {
			if($url_forward) {
				$message = "<a href=\"$url_forward\">$message</a><script>setTimeout(\"window.location.href ='$url_forward';\", ".($second*1000).");</script>";
			}
			include_once S_ROOT."./view/message.php";
		}
	}
	exit();
}

function photomessage($message, $url_forward='', $second=2) {
	global $_SGLOBAL;

	obclean();
	
	//显示
	if(empty($_SGLOBAL['inajax']) && $url_forward && empty($second)) {
		header("HTTP/1.1 301 Moved Permanently");
		header("Location: $url_forward");
	} else {
		if($_SGLOBAL['inajax']) {
			if($url_forward) {
				$message = "<a href=\"$url_forward\">$message</a><ajaxok>";
			}
			//$message = "<h1>".$_SGLOBAL['msglang']['box_title']."</h1><a href=\"javascript:;\" onclick=\"hideMenu();\" class=\"float_del\">X</a><div class=\"popupmenu_inner\">$message</div>";
			echo $message;
			//echo ob_get_contents();
		} else {
			if($url_forward) {
				$message = "<a href=\"$url_forward\">$message</a><script>setTimeout(\"window.location.href ='$url_forward';\", ".($second*1000).");</script>";
			}
			include_once S_ROOT."./view/photo.php";
		}
	}
	exit();
}

function check_username($username) {
	global $_SGLOBAL;

	$username = addslashes(trim(stripslashes($username)));
	$guestexp = '\xA1\xA1|\xAC\xA3|^Guest|^\xD3\xCE\xBF\xCD|\xB9\x43\xAB\xC8';
	$len = strlen($username);
	if($len > 15 || $len < 3 || preg_match("/\s+|^c:\\con\\con|[%,\*\"\s\<\>\&]|$guestexp/is", $username)) {
		return -1;
	} elseif($_SGLOBAL['db']->result_first("SELECT username FROM ".tname('members')." WHERE username='$username'")) {
		return -2;
	} else {
		return 1;
	}
}

function register($username, $password, $email){
	global $_SGLOBAL, $_SCONFIG;
	
	$setarr = array(
		'uid' => $newuid,
		'username' => $username,
		'password' => md5("$newuid|$_SGLOBAL[timestamp]"),//本地密码随机生成
		'dateline' => $_SGLOBAL['timestamp'],
		'lastpost' => $_SGLOBAL['timestamp'],
	);
	//更新本地用户库
	inserttable('member', $setarr, 0, true);

	//设置cookie
	ssetcookie('auth', authcode("$setarr[password]\t$setarr[uid]", 'ENCODE'), 2592000);
	ssetcookie('loginuser', $username, 31536000);
	ssetcookie('_refer', '');

	return $newuid;
}

//检查如手机号是否有效
function isphone($phone) {
    return strlen($phone) == 11 && preg_match("/^1[358]\d{9}$/", $phone);
}

function get_list($currentpage = 1, $pagesize = null, $wheresql = "", $orderby="dateline"){
	global $_SGLOBAL, $_SCONFIG;

	if($pagesize){
		if (!empty($_POST['jumpto'])) {
			$starnum = 8*($_POST['jumpto']-1);
		}else {
			$starnum = ($currentpage-1)*$pagesize;
		}	
		$limit = "limit $starnum, $pagesize";
	}
	
	$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('works')." WHERE $wheresql $orderby $limit");

	while($value = $_SGLOBAL['db']->fetch_array($query)){
		$questions[] = $value;
	}
	return $questions;
}

/**
 * 操作提示
 *
 * @param string $alert_info 提示信息
 * @param string $url        为back即为后退，否则为重定向链接
 */
function operate_alt($alert_info, $url='back') {
	$str = '<script type="text/javascript">alert("'.$alert_info.'");';
	$str.= strcasecmp($url, 'back') == 0 ? 'window.history.back(-1)' : 'window.location.href="'.$url.'"';
	$str.= '</script>';
	echo $str;
	exit;
}

//上传头像
function useravatar($uid, $ishttpurl=false) {
	global $_SC,$_SGLOBAL;
	$md5uid = md5($uid);
	$avatarpath = $_SC['avatardir'] .'/'. $md5uid[0].'/'.$md5uid[1].'/'.$md5uid.'.jpg?'.$_SGLOBAL['timestamp']; 
	if ($ishttpurl == true) $avatarpath = $_SC['sitehttp'] . $avatarpath;
	$avatarpath = str_replace('.jpg', '_s.jpg', $avatarpath);
	return $avatarpath;
} 

//上传城市图
function cityavatar($ishttpurl=false) {
	global $_SC,$_SGLOBAL;
	$code = $_SGLOBAL['timestamp'];
	$avatarpath = S_ROOT.'city/'.$code.'.jpg';
	if ($ishttpurl == true) $avatarpath = $_SC['sitehttp'] . $avatarpath;
	//$avatarpath = str_replace('.jpg', '_s.jpg', $avatarpath);
	return $avatarpath;
} 



$_SC['sendemail']['smtp_host'] =  'smtp.ceair.com';
$_SC['sendemail']['smtp_user'] =  'style@ceair.com';
$_SC['sendemail']['smtp_pwd']  =  'password';
$_SC['sendemail']['fromname']  =  '';

//发邮件
function sendmail($toaddress, $subject, $body) {
    global $_SC;

    $sendmail = $_SC['sendemail'];

	$mail = new PHPMailer();
    
	$mail->IsSMTP();                                    // set mailer to use SMTP
	$mail->Host = $sendmail['smtp_host'];  				// specify main and backup server
	$mail->SMTPAuth = true;     						// turn on SMTP authentication
	$mail->Username = $sendmail['smtp_user'];  			// SMTP username
	$mail->Password = $sendmail['smtp_pwd']; 			// SMTP password
	
	$mail->From = $sendmail['smtp_user'];
	$mail->FromName = $sendmail['fromname'];
	if (is_array($toaddress))
    	foreach($toaddress as $address) $mail->AddAddress("$address");
	else
    	$mail->AddAddress("$toaddress");
		
	$mail->CharSet = "UTF-8";
	$mail->WordWrap = 50;                                 // set word wrap to 50 characters
	$mail->IsHTML(true);                                  // set email format to HTML
	$mail->Subject = $subject;
	$mail->Body    = $body;
	//$mail->AltBody = "Form Leko test";
	return $mail->Send();
}


function ajax_jsondata($info) {
    $jsondata =  is_array($info) ? json_encode($info) : json_encode(array('res' => $info));
    echo !empty($_REQUEST['jsoncallback']) ? $_REQUEST['jsoncallback']."($jsondata)" : $jsondata;
    exit;
}

function login($username, $password) {
	global $_SGLOBAL;

	$admin_member = $_SGLOBAL['db']->fetch_first("SELECT * FROM ".tname('admin_member')." WHERE username='$username'");
	if(md5($password) == $admin_member['password']){
		ssetcookie('auth', authcode($admin_member['password']."\t".$admin_member['uid'], "CODE"));
		ssetcookie('lastpost', $admin_member['lastpost']);
		ssetcookie('ip', $admin_member['ip']);
		updatetable("admin_member", array("lastpost" => $_SGLOBAL['timestamp'], "ip" => getonlineip()), array("uid" => $admin_member['uid']));
		return true;
	} else {
		return false;
	}
}
